package com.guan.jdbc.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
/**
 * 获取数据库连接的工具类
 * @author Administrator
 *
 */
@SuppressWarnings("all")
public class DBUtil {
	// 数据源属性
	private static DruidDataSource dataScource;
	//加载配置文件的配置类
	private static Properties dbconfig;
	//定义一个线程本地对象(优化，对一个线程内共享)
	//作用于范围只有当先线程，有多个线程就会有多个实列
	private static final ThreadLocal<Connection> CONN_LOCAL = new ThreadLocal<Connection>();
	static {
		try {
			dbconfig = new Properties();
			//通过类加载器加载配置文件
			dbconfig.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
			dataScource = (DruidDataSource) DruidDataSourceFactory.createDataSource(dbconfig);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 获取数据库连接
	 * @return
	 */
	public static Connection getConnection() {
		Connection connection = null;
		try {//连接先从本地线程中拿
			connection = CONN_LOCAL.get();
			if(null == connection) {
				connection = dataScource.getConnection();
				//放到本地线程中
				CONN_LOCAL.set(connection);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return connection;
	}
	/**
	 * 关闭方法
	 */
	public static void close() {
		try {
			getConnection().close();
			CONN_LOCAL.remove();//清空本地线程
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 开启事务
	 */
	public static void openTransaction() {
		try {
			//设置自动提交为false
			getConnection().setAutoCommit(false);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 提交事务
	 */
	public static void commitTransaction() {
		try {
			//提交事务
			getConnection().commit();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 回滚事务
	 */
	public static void rollbackTransaction() {
		try {
			//回滚事务
			getConnection().rollback();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 关闭数据源
	 */
	public static void release(){
		dataScource.close();
	}
}
